package com.gzhryc.shared_device.iot.core.aliyun;

import com.gzhryc.shared_device.iot.core.IOTClient;
import com.gzhryc.shared_device.iot.core.IOTClientEvent;
import com.gzhryc.shared_device.iot.core.IOTMessage;
import com.gzhryc.shared_device.iot.core.enums.EIOTDeviceState;
import com.gzhryc.socket.SocketEvent;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AliyunIOTClientEvent implements IOTClientEvent {
	
	static Pattern pat = Pattern.compile("^/[^/]*/([^/]*)/.*$");
	
	static Pattern pat1 = Pattern.compile("^/as/mqtt/status/[^/]*/([^/]*)$");

	final String topic;
	final byte[] payload;
	final IOTClient client;
	
	String deviceSn;

	public AliyunIOTClientEvent(IOTClient client,String topic,byte[] payload) {
		this.client = client;
		this.topic = topic;
		this.payload = payload;
	}
	
	public AliyunIOTClientEvent(IOTClient client, String topic, String payload) {
		this.client = client;
		this.topic = topic;
		this.payload = Base64.decodeBase64(payload);
	}
	
	@Override
	public <T extends IOTMessage> T getMessage(Class<T> clazz) {
		if(payload != null) {
			try {
				T msg = clazz.newInstance();
				msg.setBytes(payload);
				msg.setDeviceSn(getDeviceSn());
				msg.setTopic(topic);
				return msg;
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	@Override
	public IOTMessage getMessage() {
		if(payload != null) {
			IOTMessage msg = new IOTMessage();
			msg.setBytes(payload);
			msg.setDeviceSn(getDeviceSn());
			msg.setTopic(topic);
			return msg;
		}
		return null;
	}

	@Override
	public IOTClient getClient() {
		return client;
	}

	@Override
	public String getDeviceSn() {
		if(StringUtils.isBlank(deviceSn)) {
			Matcher mat = pat1.matcher(topic);
			if(mat.find()) {
				deviceSn = mat.group(1);
			}else {
				mat = pat.matcher(topic);
				if(mat.find()) {
					deviceSn = mat.group(1);
				}
			}
		}
		return deviceSn;
	}

	@Override
	public EIOTDeviceState getState() {
		return null;
	}

	@Override
	public SocketEvent getEvent() {
		return null;
	}
}
